import 'dart:io';
import 'dart:math';

import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:bigegg/utils/dialog/xmm_dialog_utils.dart';
import 'package:bigegg/utils/xmm_toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../dialog/xmm_business_dialog.dart';
import '../../entity/articel/xmm_article_info.dart';
import '../../global/routes/xmm_routes.dart';
import '../../res/xmm_img.dart';
import '../../widget/image/xmm_circle_cached_network_image.dart';

class XmmArticleListView extends StatefulWidget {
  const XmmArticleListView(
      {super.key, required this.articleList, this.paddingBottom});

  final Iterable<XmmArticleInfo> articleList;

  final double? paddingBottom;

  @override
  State<StatefulWidget> createState() {
    return XmmArticleListViewState();
  }
}

class XmmArticleListViewState extends State<XmmArticleListView> {
  @override
  Widget build(BuildContext context) {
    return articleListWidget(widget.articleList);
  }

  void showMoreDialog(XmmArticleInfo item) {
    XmmBusinessDialog.showMoreDialog(item.wallUser?.userId ?? "");
  }

  void deleteMyArticle(XmmArticleInfo item) {
    XmmDialogUtils.showConfirmDialog(
      "Are you sure to delete this content?",
      () {
        XmmAccountManager.instance.removeArticleByMy(item);
        XmmToastUtils.show("Delete Successfully");
      },
    );
  }

  Widget articleListWidget(Iterable<XmmArticleInfo> articleList) {
    return Flexible(
      child: Container(
        padding: const EdgeInsets.only(left: 20, right: 15),
        child: ListView.separated(
          separatorBuilder: (BuildContext context, int index) =>
              const Divider(height: 10, color: Colors.transparent),
          padding: EdgeInsets.only(bottom: widget.paddingBottom ?? 100.w),
          shrinkWrap: true,
          itemCount: articleList.length,
          itemBuilder: (context, index) {
            var item = articleList.elementAt(index);
            return GestureDetector(
              child: Card(
                color: Colors.white,
                elevation: 3,
                shadowColor: const Color(0x44000000),
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12)),
                ),
                child: Container(
                  height: 294.w,
                  padding: EdgeInsets.only(
                    left: 10.w,
                    right: 10.w,
                    top: 10.h,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      topWidget(item),
                      const SizedBox(height: 5),
                      Text(
                        item.title ?? "",
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFF404040),
                        ),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        item.description ?? "",
                        style: TextStyle(
                          fontSize: 11.sp,
                          color: const Color(0x80000000),
                        ),
                      ),
                      imageContent(item)
                    ],
                  ),
                ),
              ),
              onTap: () => Get.toNamed(
                XmmRoutes.articleDetailPage,
                arguments: item,
              ),
            );
          },
        ),
      ),
    );
  }

  Widget topWidget(XmmArticleInfo item) {
    var isMyArticle =
        item.wallUser?.userId == XmmAccountManager.instance.user.userId;
    return Container(
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          GestureDetector(
            onTap: () => XmmRoutes.routePersonPage(item.wallUser?.userId ?? ""),
            child: XmmCircleCachedNetworkImage(
              width: 34.w,
              height: 34.w,
              imageUrl: item.wallUser?.getAvatarUrl ?? "",
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 8),
              child: Text(
                item.wallUser?.nickname ?? "",
                style:
                    TextStyle(fontSize: 16.sp, color: const Color(0xFF404040)),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          GestureDetector(
            child: Image.asset(
              isMyArticle ? XmmImg.deleteArticleIcon : XmmImg.homeMoreIcon,
              width: 18.w,
              height: 16.w,
            ),
            onTap: () {
              if (isMyArticle) {
                deleteMyArticle(item);
              } else {
                showMoreDialog(item);
              }
            },
          )
        ],
      ),
    );
  }

  Widget imageItemWidget(
    XmmArticleInfo item,
    double angle,
    String imgPath,
  ) {
    var isMyArticle =
        item.wallUser?.userId == XmmAccountManager.instance.user.userId;
    return Column(
      children: [
        Transform.rotate(
          angle: angle,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: isMyArticle
                ? Image.file(
                    File(imgPath),
                    fit: BoxFit.cover,
                    height: 204.w,
                    width: 148.w,
                  )
                : Image.asset(
                    imgPath,
                    fit: BoxFit.cover,
                    height: 204.w,
                    width: 148.w,
                  ),
          ),
        )
      ],
    );
  }

  Widget imageContent(XmmArticleInfo item) {
    var isMyArticle =
        item.wallUser?.userId == XmmAccountManager.instance.user.userId;
    if ((item.content?.length ?? 0) >= 2) {
      var imageList = item.content?.reversed;
      return Flexible(
        child: Stack(
          children: [
            Positioned(
              left: 10.w,
              bottom: -17.w,
              child: imageItemWidget(
                item,
                -7.54 * pi / 180.0,
                imageList?.elementAt(0) ?? "",
              ),
            ),
            Positioned(
              right: 11.w,
              bottom: -7.w,
              child: imageItemWidget(
                item,
                3.11 * pi / 180.0,
                imageList?.elementAt(1) ?? "",
              ),
            ),
            (imageList?.length ?? 0) >= 3
                ? Positioned(
                    left: 0,
                    right: 0,
                    bottom: -40.w,
                    child: imageItemWidget(
                      item,
                      -3.11 * pi / 180.0,
                      imageList?.elementAt(2) ?? "",
                    ),
                  )
                : Container(),
          ],
        ),
      );
    } else {
      return Expanded(
        child: Padding(
          padding: EdgeInsets.only(top: 14.w, bottom: 12.w),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              image: isMyArticle
                  ? DecorationImage(
                      image: FileImage(File(item.content?.first ?? "")),
                      fit: BoxFit.cover,
                    )
                  : DecorationImage(
                      image: AssetImage(item.content?.first ?? ""),
                      fit: BoxFit.cover,
                    ),
            ),
          ),
        ),
      );
    }
  }
}
